<template>
  <a-select
    v-model:value="valueProxy"
    :disabled="disabled"
    :dropdown-match-select-width="dropdownMatchSelectWidth"
    :dropdown-style="dropdownStyle"
    :placeholder="placeholder"
    :show-search="showSearch"
    :style="style"
    :mode="mode"
    @change="handleChange"
    @search="handleSearch"
    @dropdown-visible-change="handleDropdownVisibleChange"
  >
    <!-- 自定义下拉内容 -->
    <template #dropdownRender>
      <div class="custom-dropdown">
        <!-- 表格作为下拉选项 -->
        <a-table
          :columns="columns"
          :custom-row="customRow"
          :data-source="filteredOptions"
          :loading="loading"
          :pagination="pagination"
          :row-key="rowKey"
          :scroll="{ y: scrollY }"
          :show-header="showHeader"
          size="small"
          @row-click="handleTableRowClick"
        >
          <template v-for="slot in Object.keys($slots)" #[slot]="scope">
            <slot :name="slot" v-bind="scope"></slot>
          </template>
        </a-table>
      </div>
    </template>
  </a-select>
</template>

<script setup>
  import { computed, ref, watch } from 'vue';

  const props = defineProps({
    modelValue: {
      type: [String, Number, Array],
      default: null,
    },
    options: {
      type: Array,
      required: true,
      default: () => [],
    },
    columns: {
      type: Array,
      required: true,
      validator: (value) => {
        return value.every((col) => 'title' in col && 'dataIndex' in col && 'key' in col);
      },
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    style: {
      type: Object,
      default: () => ({ width: '100%' }),
    },
    filterKey: {
      type: String,
      default: 'value',
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    debounce: {
      type: Number,
      default: 300,
    },
    dropdownStyle: {
      type: Object,
      default: () => ({ maxHeight: '400px', overflow: 'auto' }),
    },
    dropdownMatchSelectWidth: {
      type: [Boolean, Number],
      default: 500,
    },
    showSearch: {
      type: Boolean,
      default: true,
    },
    showHeader: {
      type: Boolean,
      default: true,
    },
    scrollY: {
      type: Number,
      default: 250,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    pagination: {
      type: [Boolean, Object],
      default: false,
    },
    mode: {
      type: String,
      default: 'default', // 'default' 或 'multiple'
      validator: (value) => ['default', 'multiple'].includes(value),
    },
  });

  const emit = defineEmits(['update:modelValue', 'select', 'change', 'search', 'dropdownVisibleChange']);

  const valueProxy = computed({
    get() {
      // 多选模式下确保返回数组
      if (props.mode === 'multiple') {
        return Array.isArray(props.modelValue) ? props.modelValue : [];
      }
      return props.modelValue;
    },
    set(value) {
      emit('update:modelValue', value);
    },
  });

  const searchText = ref('');
  const filteredOptions = ref([...props.options]);
  let debounceTimer = null;

  const handleSearch = (value) => {
    searchText.value = value;
    emit('search', value);

    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      if (!value) {
        filteredOptions.value = [...props.options];
        return;
      }

      filteredOptions.value = props.options.filter((item) => {
        return Object.keys(item).some((key) => String(item[key]).toLowerCase().includes(value.toLowerCase()));
      });
    }, props.debounce);
  };

  const handleChange = (value) => {
    valueProxy.value = value;
    emit('change', value);
  };

  const handleDropdownVisibleChange = (open) => {
    emit('dropdownVisibleChange', open);
    if (!open) {
      searchText.value = '';
      filteredOptions.value = [...props.options];
    }
  };

  const handleTableRowClick = (record) => {
    const value = record[props.filterKey];

    if (props.mode === 'multiple') {
      const currentValue = Array.isArray(valueProxy.value) ? valueProxy.value : [];
      const newValue = currentValue.includes(value) ? currentValue.filter((v) => v !== value) : [...currentValue, value];
      valueProxy.value = newValue;
      emit('select', { value, record });
    } else {
      valueProxy.value = value;
      emit('select', { value, record });
    }
  };

  const customRow = (record) => {
    return {
      onClick: () => {
        handleTableRowClick(record);
      },
      style: {
        cursor: 'pointer',
        backgroundColor: isSelected(record) ? '#f5f5f5' : 'inherit',
      },
    };
  };

  const isSelected = (record) => {
    const value = record[props.filterKey];
    if (props.mode === 'multiple') {
      return Array.isArray(valueProxy.value) && valueProxy.value.includes(value);
    }
    return valueProxy.value === value;
  };

  watch(
    () => props.options,
    (newVal) => {
      filteredOptions.value = [...newVal];
    },
    { deep: true }
  );
</script>

<style scoped>
  .custom-dropdown {
    background: #fff;
    border-radius: 2px;
  }

  /* 高亮选中行 */
  :deep(.ant-table-tbody > tr.ant-table-row-selected > td) {
    background-color: paleturquoise;
  }

  /* 调整表格样式 */
  :deep(.ant-table-small .ant-table-thead > tr > th) {
    padding: 8px;
  }

  :deep(.ant-table-small .ant-table-tbody > tr > td) {
    padding: 8px;
  }
</style>